import React from 'react';
import {Platform} from 'react-native';
import {NavigationContainer, useTheme} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {navigationRef} from '@/utils/navigation';
import {HapticTab} from '@/components/HapticTab';
import {NotFound} from '@/components/NotFound';
import {tabRoutes, authRoutes, stackRoutes} from '@/routes';
import { useSelector } from 'react-redux';
import { RootState } from '@/stores';
import {themes} from '@/constants/Themes';

const Stack = createNativeStackNavigator();
const Tab = createBottomTabNavigator();

function TabNavigator() {
  const {colors} = useTheme();

  return (
    <Tab.Navigator
      screenOptions={{
        tabBarActiveTintColor: colors.primary,
        tabBarInactiveTintColor: colors.text,
        headerShown: false,
        tabBarButton: HapticTab,
        tabBarStyle: Platform.select({
          ios: {
            position: 'absolute',
          },
          default: {},
        }),
      }}>
      {tabRoutes.map(({path, element, options}) => (
        <Tab.Screen
          key={path}
          name={path}
          component={element!}
          options={options!}
        />
      ))}
    </Tab.Navigator>
  );
}

function AuthNavigator() {
  return (
    <Stack.Navigator screenOptions={{headerShown: false}}>
      {authRoutes.map(({path, element, options}) => (
        <Stack.Screen
          key={path}
          name={path}
          component={element!}
          options={options!}
        />
      ))}
    </Stack.Navigator>
  );
}

function StackNavigator() {
  return (
    <Stack.Navigator
      screenOptions={{
        animation: 'slide_from_right',
        headerShown: false,
        gestureEnabled: true,
        fullScreenGestureEnabled: true,
      }}>
      {stackRoutes.map(({path, element, options}) => (
        <Stack.Screen
          key={path}
          name={path}
          component={element!}
          options={options!}
        />
      ))}
    </Stack.Navigator>
  );
}

export function RootNavigator() {
  const theme = useSelector((state: RootState) => state.theme.theme);
  const token = useSelector((state: RootState) => state.user.token);
  const navigationTheme = themes[theme].navigation;
  const initialRouteName = token ? 'tab' : 'auth'; 

  return (
    <NavigationContainer ref={navigationRef} fallback={<NotFound />} theme={navigationTheme}>
      <Stack.Navigator screenOptions={{headerShown: false}} initialRouteName={initialRouteName}>
        <Stack.Screen name="auth" component={AuthNavigator} />
        <Stack.Screen name="tab" component={TabNavigator} />
        <Stack.Screen name="stack" component={StackNavigator} />
        <Stack.Screen name="+not-found" component={NotFound} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default RootNavigator;
